package com.wangjin.javaProject.address;

import com.wangjin.javaProject.utils.Base58;
import com.wangjin.javaProject.utils.Hash;

import java.security.InvalidAlgorithmParameterException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.ECPublicKey;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.ECPoint;
import java.util.Arrays;

/**
 * @Creator: WangJin
 * @desc:   该类用于生成比特币地址
 * @Creation Data: 2021/12/25 21:07
 **/
public class Address {
    /**
     * Java中原生，生成一堆密钥，并将密钥对对象KeyPair返回
     * @return 生成的密钥对
     */
    public KeyPair generateKeys(){
        try {
            KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
            //secp256k1,secp256r1
            ECGenParameterSpec spec = new ECGenParameterSpec("secp256k1");
            generator.initialize(spec);
            return generator.generateKeyPair();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 根据提供的密钥对数据，推导生成一个原始格式的比特币地址，并返回
     * @param keyPair 提供的密钥对信息
     * @return 推导生成的比特币地址
     */
    public String newAddress(KeyPair keyPair){
        ECPublicKey publickKey = (ECPublicKey) keyPair.getPublic();
        ECPoint point = publickKey.getW();
        //原始格式的公钥
        byte[] pubKey = toUncomCompressPubKey(point);

        //对公钥进行哈希计算
        byte[] pubKeyHash256 = Hash.SHA256(pubKey);
        byte[] pubHash = Hash.RIPEMD160(pubKeyHash256);

        byte[] version = new byte[1];
        version[0] = 0x00;//版本号

        byte[] ver_pubhash = new byte[version.length + pubHash.length];
        System.arraycopy(version,0,ver_pubhash,0,version.length);
        System.arraycopy(pubHash,0,ver_pubhash,1,pubHash.length);

        //双哈希，去前4字节
        byte[] hash1 = Hash.SHA256(ver_pubhash);
        byte[] hash2 = Hash.SHA256(hash1);
        byte[] check = new byte[4];
        System.arraycopy(hash2,0,check,0,check.length);

        byte[] ver_pubhash_check = new byte[ver_pubhash.length + check.length];
        System.arraycopy(ver_pubhash,0,ver_pubhash_check,0,ver_pubhash.length);
        System.arraycopy(check,0,ver_pubhash_check,ver_pubhash.length,check.length);

        //对拼接到的字节数组进行base58编码
        return Base58.encode(ver_pubhash_check);
    }

    /**
     *  校验比特吗地址是否符合规范，并返回校验结果
     * @param addr 要校验的字符串
     * @return 校验结果turn表示符合规范，false表示不符合
     */
    public boolean validateAddr(String addr){
        if ("".equals(addr) || addr == null){
            return false;
        }
        byte[] ver_pubhash_check = Base58.decode(addr);
        if (ver_pubhash_check.length <4){
            return false;
        }
        byte[] check = new byte[4];
        System.arraycopy(ver_pubhash_check,ver_pubhash_check.length-4,check,0,4 );

        byte[] ver_pubhash = new byte[ver_pubhash_check.length-4];
        System.arraycopy(ver_pubhash_check,0,ver_pubhash,0,ver_pubhash.length);

        //双哈希取前4个字节
        byte[] hash1 = Hash.SHA256(ver_pubhash);
        byte[] hash2 = Hash.SHA256(hash1);
        if (hash2 == null){
            return false;
        }
        byte[] check_sum = new byte[4];
        System.arraycopy(hash2,0,check_sum,0,check_sum.length);

        //比较两个字节数组是否相等
        return Arrays.equals(check,check_sum);
    }

    /**
     *  该方法用于生成非压缩的公钥数据，并返回
     * @return 非压缩格式公钥
     */
    public static byte[]toUncomCompressPubKey(ECPoint point){
        byte[] xBytes = point.getAffineX().toByteArray();
        byte[] yBytes = point.getAffineY().toByteArray();
        //原始格式： 04 + x坐标 + y坐标 = 65字节
        byte[] pubKey = new byte[1+2*32];
        pubKey[0] = 04;
        if (xBytes.length == 32){
            //通过拷贝来完成数据的拼接
            System.arraycopy(xBytes,0,pubKey,1,xBytes.length);
        }else if (xBytes.length > 32){
            //只取后32
            System.arraycopy(xBytes,1,pubKey,1,32);
        }
        //y坐标
        if (yBytes.length == 32){
            System.arraycopy(yBytes,0,pubKey,33,yBytes.length);
        }else if (yBytes.length > 32){
            System.arraycopy(yBytes,1,pubKey,33,32);
        }
        return pubKey;
    }
}
